import requests
from common.logger import log
from urllib import parse
#是否记录接口请求和响应
is_log = True

#接口请求和响应的日志格式
def save_log(response:requests.request, is_log=True):
    if is_log is True:
        #对url进行解码处理
        urldata = parse.unquote(response.request.url)
        if response.request.body:
            log.info(
                "\n{}\n{}\n{}\n\n{}\n{}\n{}".format(
                    "-----------------------Request----------------------->",
                    response.request.method + " " + urldata,
                    "请求body："+ str(response.request.body,encoding="utf8"),
                    "<----------------------Response------------------------",
                    "Status code:" + str(response.status_code),
                    response.text
                ))
        else:
            log.info("\n{}\n{}\n{}\n\n{}\n{}\n{}".format(
                    "-----------------------Request----------------------->",
                    response.request.method + " " + urldata,
                    "请求body：无",
                    "<----------------------Response------------------------",
                    "Status code:" + str(response.status_code),
                    response.text
                ))
    else:
        pass


class HttpRequests:
    def __init__(self):
        """session管理器"""
        self.session = requests.session()

    #封装request，增加日志输出
    def request(self, method, url, params=None, data=None, json=None, headers=None, **kwargs):
        try:
            response = self.session.request(method,url, params=params, data=data, json=json, headers=headers,**kwargs)
            #response.encoding = response.apparent_encoding
            save_log(response, is_log=is_log)
        except Exception as E:
            print(E)
        return self.session.request(method,url, params=params, data=data, json=json, headers=headers,**kwargs)

    def get(self,url, params=None, **kwargs):
        return self.request('get', url, params=params, **kwargs)

    def post(self,url, data=None, json=None, **kwargs):
        return self.request('post', url, data=data, json=json, **kwargs)

    def put(self,url, data=None, **kwargs):
        return self.request('put', url, data=data, **kwargs)

    def delete(self,url, **kwargs):
        return self.request('delete', url, **kwargs)

    def close_session(self):
        """关闭session"""
        self.session.close()


if __name__ == '__main__':
    url = "https://qixin.bonc.com.cn/eframe/attence/query.e"

    param = {"_data":'{"EMPLOYEE_NO":"290135","ACCT_ID":"202112","DAY_OR_MONTH":"month"}',
             "signature":"QUdzlUMISU4MJX+RL1ggig=="}
    req = HttpRequests()
    res = req.get(url, params=param)